<template>
  <div class="app-container">
    <div class="top">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/static-site/static-site/' }">静态网站管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{ siteName }} - 分类管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="top">
      <el-input
        v-model="kwInput"
        placeholder="输入分类名称进行筛选"
        class="input-with-select"
        clearable
        @keyup.native.enter="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </el-input>
      <el-button
        type="primary"
        class="el-icon-plus add-btn"
        :disabled="listLoading"
        @click="handleAction('create', '添加分类')"
      >添加分类
      </el-button>

      <!-- AI任务组件 -->
      <AITask
        v-if="aiTaskParams.task_name === 'ai_extract_anchor_keywords'"
        ref="aiExtractKeywordsTask"
        :params="aiTaskParams"
        task-name="ai_extract_anchor_keywords"
        show-name="AI提取锚文本关键词"
        dialog-title="AI提取锚文本关键词"
        button-text="AI提取关键词"
        button-type="success"
        button-icon="el-icon-magic-stick"
        dialog-width="70%"
        :show-apply-button="true"
        @apply="handleApplyKeywords"
      />

      <AITask
        v-if="aiTaskParams.task_name === 'ai_generate_category_page'"
        ref="aiGenerateCategoryTask"
        :params="aiTaskParams"
        task-name="ai_generate_category_page"
        show-name="AI生成分类页面"
        dialog-title="AI生成分类页面HTML内容"
        button-text="AI生成分类页面"
        button-type="success"
        button-icon="el-icon-magic-stick"
        dialog-width="80%"
        :show-apply-button="true"
        @final-result="handleAICategoryResult"
      />
    </div>

    <el-table
      v-loading.body="listLoading"
      :data="data"
      border
      fit
      highlight-current-row
      style="width: 100%"
      row-key="id"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >

      <el-table-column align="left" label="分类名称" prop="name" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="别名" prop="slug" width="150">
        <template slot-scope="scope">
          <el-tag type="info">{{ scope.row.slug }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="描述">
        <template slot-scope="scope">
          <el-tooltip effect="dark" :content="scope.row.description" placement="top">
            <span>{{ scope.row.description | truncate(50) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column align="center" label="排序" prop="sort_order" width="80" />

      <el-table-column align="center" label="状态" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_active ? 'success' : 'danger'">
            {{ scope.row.is_active ? '激活' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="HTML内容" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.html_content && scope.row.html_content.trim()" type="success" size="small">
            有内容
          </el-tag>
          <el-tag v-else type="info" size="small">
            暂无
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="创建时间" prop="create_at" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.create_at }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="320">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handlePreviewEdit(scope.row)">预览修改</el-button>
          <el-button size="mini" type="info" @click="handleAction('edit', scope.row)">编辑</el-button>
          <el-button size="mini" plain title="重构菜单" @click="handleRebuildCategoryMenu(scope.row)">
            <i class="el-icon-menu" />
          </el-button>
          <el-button size="mini" type="success" plain title="快速导航替换" @click="handleFastNavigationReplace(scope.row)">
            <i class="el-icon-lightning" />
          </el-button>
          <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="total>0"
      background
      :current-page="listQuery.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="listQuery.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <el-dialog
      class="mt-dialog"
      :title="title"
      :width="width"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="100px">
        <el-form-item v-if="action !== 'delete'" label="分类名称">
          <el-input v-model="temp.name" placeholder="请输入分类名称" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="分类别名">
          <el-input v-model="temp.slug" placeholder="请输入分类别名（用于URL）" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="父分类">
          <el-select v-model="temp.parent" placeholder="请选择父分类（可选）" clearable filterable>
            <el-option
              v-for="item in parentCategories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="temp.id === item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="分类描述">
          <el-input v-model="temp.description" type="textarea" :rows="3" placeholder="请输入分类描述" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="锚文本关键词">
          <div style="display: flex; align-items: flex-start; gap: 10px;">
            <el-input v-model="temp.anchor_text_keywords" type="textarea" :rows="2" placeholder="请输入锚文本关键词列表，每行一个" style="flex: 1;" />
            <el-button
              type="success"
              size="small"
              icon="el-icon-magic-stick"
              @click="handleAITask"
            >AI提取
            </el-button>
          </div>
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="分类提示词">
          <el-input v-model="temp.prompt" type="textarea" :rows="4" placeholder="请输入分类提示词" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="模板选择">
          <div style="display: flex; align-items: flex-start; gap: 10px;">
            <el-select v-model="temp.template" placeholder="请选择模板（可选）" clearable filterable style="flex: 1;">
              <el-option
                v-for="item in templates"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-tooltip
              content="根据选中的模板和当前分类信息，使用AI生成分类页面HTML内容。需要先保存分类，然后选择模板。"
              placement="top"
            >
              <el-button
                type="success"
                size="small"
                icon="el-icon-magic-stick"
                :disabled="!temp.template || !temp.name"
                @click="handleAIGenerateWithTemplate"
              >AI创建HTML
              </el-button>
            </el-tooltip>
          </div>
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="内部链接地址">
          <el-input v-model="temp.inner_link_url" placeholder="请输入内部链接地址（可选）" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="最多链接产品数量">
          <el-input-number v-model="temp.max_link_products" :min="0" :max="50" placeholder="AI生成时最多包含的产品链接数量，0为不添加" />
          <span style="color: #999; font-size: 12px; margin-left: 10px;">设置为0则不添加产品链接，默认12个</span>
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="HTML内容">
          <div style="display: flex; align-items: flex-start; gap: 10px;">
            <el-input v-model="temp.html_content" type="textarea" :rows="5" placeholder="请输入HTML内容（可选）" style="flex: 1;" />
            <div style="display: flex; flex-direction: column; gap: 5px;">
              <el-button
                type="success"
                size="small"
                icon="el-icon-magic-stick"
                @click="handleAIGenerateCategory"
              >AI生成
              </el-button>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-view"
                @click="handleQuickPreview"
              >预览
              </el-button>
            </div>
          </div>
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="排序">
          <el-input-number v-model="temp.sort_order" :min="0" :max="9999" placeholder="数字越小排序越前" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="状态">
          <el-switch v-model="temp.is_active" active-text="激活" inactive-text="停用" />
        </el-form-item>

        <div v-if="action === 'delete'" style="text-align: center; font-size: 16px;">
          确认要删除分类 <strong>{{ temp.name }}</strong> 吗？
          <br><br>
          <el-alert title="警告：删除分类将同时删除所有子分类和相关页面数据！" type="warning" show-icon />
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- AI任务配置对话框 -->
    <el-dialog
      class="ai-config-dialog"
      title="AI提取锚文本关键词 - 配置"
      :width="'60%'"
      :visible.sync="aiConfigDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="aiConfigForm" label-position="left" label-width="120px">
        <el-form-item label="输入方式">
          <el-radio-group v-model="aiConfigForm.inputMethod">
            <el-radio label="title">手动输入标题</el-radio>
            <el-radio label="page">选择静态页面</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="aiConfigForm.inputMethod === 'title'" label="标题内容">
          <el-input
            v-model="aiConfigForm.inputTitle"
            type="textarea"
            :rows="3"
            placeholder="请输入页面标题或内容描述"
          />
        </el-form-item>

        <el-form-item v-if="aiConfigForm.inputMethod === 'page'" label="选择页面">
          <el-select
            v-model="aiConfigForm.selectedPageId"
            placeholder="请选择静态页面"
            filterable
            style="width: 100%"
            @focus="getStaticPageList"
          >
            <el-option
              v-for="page in staticPages"
              :key="page.id"
              :label="page.title"
              :value="page.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="页面类型">
          <el-switch
            v-model="aiConfigForm.isB2B"
            active-text="B2B落地页"
            inactive-text="普通页面"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="aiConfigDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="startAITask">开始提取</el-button>
      </span>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog
      title="分类HTML内容预览"
      :visible.sync="previewVisible"
      width="90%"
      top="5vh"
      :close-on-click-modal="false"
    >
      <div class="preview-container">
        <div class="preview-header">
          <el-tag type="info">{{ previewCategory.name }}</el-tag>
          <span style="margin-left: 10px; color: #666;">{{ previewCategory.slug }}</span>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-full-screen"
            style="float: right;"
            @click="openFullPreview"
          >
            全屏预览
          </el-button>
        </div>
        <div class="preview-iframe-container">
          <iframe
            ref="previewFrame"
            :srcdoc="previewHtml"
            width="100%"
            height="600px"
            frameborder="0"
            sandbox="allow-scripts allow-same-origin"
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 全屏预览对话框 -->
    <el-dialog
      title="全屏预览"
      :visible.sync="fullPreviewVisible"
      width="95%"
      top="2vh"
      :close-on-click-modal="false"
      custom-class="full-preview-dialog"
    >
      <div class="full-preview-container">
        <iframe
          :srcdoc="previewHtml"
          width="100%"
          height="80vh"
          frameborder="0"
          sandbox="allow-scripts allow-same-origin"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="fullPreviewVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 菜单选择对话框 -->
    <el-dialog
      title="选择要替换的菜单"
      :visible.sync="menuSelectDialogVisible"
      width="50%"
      :close-on-click-modal="false"
    >
      <div class="menu-select-content">
        <p style="margin-bottom: 20px; color: #606266;">
          请选择要用于替换分类 <strong>{{ currentNavigationCategory ? currentNavigationCategory.name : '' }}</strong> 导航部分的菜单：
        </p>
        <el-select
          v-model="selectedMenuId"
          placeholder="请选择菜单"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="menu in menuList"
            :key="menu.id"
            :label="`${menu.name} (${getMenuTypeLabel(menu.menu_type)})`"
            :value="menu.id"
          >
            <span style="float: left">{{ menu.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ getMenuTypeLabel(menu.menu_type) }}</span>
          </el-option>
        </el-select>
        <div style="margin-top: 15px; padding: 10px; background: #f0f9ff; border: 1px solid #b3d8ff; border-radius: 4px; font-size: 13px; color: #1f2937;">
          <i class="el-icon-info" style="color: #1890ff;" />
          <strong>功能说明：</strong>快速导航替换将仅替换分类页面中的导航菜单部分，保持其他内容不变，有效节省AI成本。
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="menuSelectDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          :disabled="!selectedMenuId"
          @click="confirmNavigationReplace"
        >
          确认替换
        </el-button>
      </span>
    </el-dialog>

    <!-- AI菜单重构日志对话框 -->
    <el-dialog
      :title="currentRebuildCategory ? `重构分类菜单: ${currentRebuildCategory.name}` : '重构分类菜单'"
      :visible.sync="menuRebuildLogVisible"
      width="70%"
      :close-on-click-modal="false"
      :show-close="!menuRebuildLoading"
    >
      <div class="menu-rebuild-log" style="height: 400px; overflow-y: auto; background: #f5f5f5; padding: 10px; border-radius: 4px; font-family: monospace; font-size: 12px; line-height: 1.4; white-space: pre-wrap;">
        {{ menuRebuildLog }}
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="menuRebuildLoading"
          :disabled="menuRebuildLoading"
          @click="menuRebuildLogVisible = false"
        >
          {{ menuRebuildLoading ? '重构中...' : '关闭' }}
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getStaticSiteCategoryList,
  createStaticSiteCategory,
  updateStaticSiteCategory,
  deleteStaticSiteCategory,
  getHtmlTemplateList,
  getStaticSitePageList,
  getStaticSiteMenuList,
  aiRebuildCategoryMenuStream,
  aiRebuildCategoryNavigationOnly
} from '@/api/spider/static_site'
import AITask from '@/components/AITask/index.vue'

export default {
  name: 'StaticSiteCategory',
  components: {
    AITask
  },
  filters: {
    truncate(value, length = 50) {
      if (!value) return ''
      if (value.length <= length) return value
      return value.slice(0, length) + '...'
    }
  },
  data() {
    return {
      data: [],
      listLoading: true,
      kwInput: '',
      listQuery: {
        page: 1,
        pageSize: 20
      },
      total: 0,
      siteId: null,
      siteName: '',
      parentCategories: [],
      templates: [],

      action: null,
      dialogVisible: false,
      title: '',
      temp: {
        name: '',
        slug: '',
        parent: null,
        description: '',
        anchor_text_keywords: '',
        prompt: '',
        inner_link_url: '',
        template: null,
        html_content: '',
        max_link_products: 12,
        sort_order: 0,
        is_active: true
      },
      width: '50%',

      // AI任务相关
      staticPages: [],
      aiConfigDialogVisible: false,
      aiConfigForm: {
        inputMethod: 'title',
        inputTitle: '',
        selectedPageId: null,
        isB2B: true
      },
      aiTaskParams: {
        task_name: null
      },

      // 预览相关
      previewVisible: false,
      fullPreviewVisible: false,
      previewCategory: {},
      previewHtml: '',

      // AI菜单重构相关
      menuRebuildLoading: false,
      menuRebuildLogVisible: false,
      menuRebuildLog: '',
      currentRebuildCategory: null,

      // 菜单选择相关
      menuSelectDialogVisible: false,
      menuList: [],
      selectedMenuId: null,
      currentNavigationCategory: null
    }
  },
  created() {
    this.siteId = this.$route.query.site_id
    this.siteName = this.$route.query.site_name || '未知网站'
    if (!this.siteId) {
      this.$message.error('缺少网站ID参数')
      this.$router.push('/static-site/static-site/')
      return
    }
    this.getList()
    this.getTemplateList()
  },
  methods: {
    resetTemp() {
      this.temp = {
        name: '',
        slug: '',
        parent: null,
        description: '',
        anchor_text_keywords: '',
        prompt: '',
        inner_link_url: '',
        template: null,
        html_content: '',
        max_link_products: 12,
        sort_order: 0,
        is_active: true,
        site: this.siteId
      }
    },
    getTemplateList() {
      const params = {
        site_id: this.siteId,
        pagesize: 100
      }

      getHtmlTemplateList(params).then(response => {
        if (response.success) {
          this.templates = response.data.data || []
        }
      }).catch(err => {
        console.log('获取模板列表失败:', err)
      })
    },
    getList() {
      this.listLoading = true
      const params = {
        page: this.listQuery.page,
        pageSize: this.listQuery.pageSize,
        site_id: this.siteId
      }
      if (this.kwInput) {
        params.search = this.kwInput
      }

      getStaticSiteCategoryList(new URLSearchParams(params).toString())
        .then(response => {
          if (response.success) {
            this.data = response.data.data
            this.total = response.data.total
            this.parentCategories = response.data.data.filter(item => !item.parent)
          } else {
            this.$message.error('获取数据失败：' + response.msg)
          }
          this.listLoading = false
        }).catch(err => {
          console.log(err)
          this.$message.error('获取数据失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '70%'
          this.title = '添加分类'
          this.resetTemp()
          this.dialogVisible = true
          break
        case 'edit':
          this.width = '70%'
          this.title = '编辑分类'
          this.temp = Object.assign({}, row)
          this.temp.site = this.siteId
          // 修复字段映射：后端返回template_id，前端使用template
          this.temp.template = this.temp.template_id || null
          this.dialogVisible = true
          break
        case 'delete':
          this.width = '40%'
          this.title = '删除确认'
          this.temp = Object.assign({}, row)
          this.dialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          createStaticSiteCategory(_data).then(response => {
            if (response.success) {
              this.dialogVisible = false
              this.getList()
              this.notify('添加成功')
            } else {
              this.$message.error('添加失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('添加失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
        case 'edit':
          updateStaticSiteCategory(_data.id, _data).then(response => {
            if (response.success) {
              this.dialogVisible = false
              this.getList()
              this.notify('更新成功')
            } else {
              this.$message.error('更新失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('更新失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
        case 'delete':
          deleteStaticSiteCategory(_data.id).then(response => {
            if (response.success) {
              this.dialogVisible = false
              this.getList()
              this.notify('删除成功')
            } else {
              this.$message.error('删除失败：' + response.msg)
            }
          }).catch(err => {
            this.$message.error('删除失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
          })
          return
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handlePageChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },
    // AI任务相关方法
    handleAITask() {
      // 重置配置表单
      this.aiConfigForm = {
        inputMethod: 'title',
        inputTitle: '',
        selectedPageId: null,
        isB2B: true
      }
      this.aiConfigDialogVisible = true
    },
    getStaticPageList() {
      const params = {
        site_id: this.siteId,
        pagesize: 100
      }

      getStaticSitePageList(new URLSearchParams(params).toString())
        .then(response => {
          if (response.success) {
            this.staticPages = response.data.data || []
          }
        }).catch(err => {
          console.log('获取页面列表失败:', err)
        })
    },
    startAITask() {
      // 验证输入
      if (this.aiConfigForm.inputMethod === 'title' && !this.aiConfigForm.inputTitle.trim()) {
        this.$message.error('请输入标题内容')
        return
      }

      if (this.aiConfigForm.inputMethod === 'page' && !this.aiConfigForm.selectedPageId) {
        this.$message.error('请选择静态页面')
        return
      }

      // 构建AI任务参数
      this.aiTaskParams = {
        task_name: 'ai_extract_anchor_keywords',
        site_id: this.siteId,
        input_method: this.aiConfigForm.inputMethod,
        is_b2b: this.aiConfigForm.isB2B
      }

      if (this.aiConfigForm.inputMethod === 'title') {
        this.aiTaskParams.content = this.aiConfigForm.inputTitle
      } else {
        this.aiTaskParams.page_id = this.aiConfigForm.selectedPageId
      }

      // 关闭配置对话框
      this.aiConfigDialogVisible = false

      // 显示AITask组件并触发开始分析
      this.$nextTick(() => {
        if (this.$refs.aiExtractKeywordsTask) {
          this.$refs.aiExtractKeywordsTask.handleShowDialog()
        }
      })
    },
    handleApplyKeywords(result) {
      // 处理AITask组件的应用事件
      console.log('AI提取结果:', result)
      console.log('result类型:', typeof result)
      if (typeof result === 'object') {
        console.log('result.final_result:', result.final_result)
        console.log('result.content:', result.content)
        console.log('result.result:', result.result)
      }

      // 支持新的数据格式（对象）和旧的数据格式（字符串）
      let contentToProcess = ''
      if (typeof result === 'object' && result !== null) {
        // 新格式：优先使用final_result，其次使用content，最后使用result
        contentToProcess = result.final_result || result.content || result.result || ''
      } else if (typeof result === 'string') {
        // 旧格式：直接使用字符串
        contentToProcess = result
      }

      // 从content中解析关键词数据
      let keywordsData = null
      if (contentToProcess.indexOf('<!--FINAL_RESULT:') !== -1) {
        try {
          const jsonStart = contentToProcess.indexOf('<!--FINAL_RESULT:') + 18
          const jsonEnd = contentToProcess.indexOf('-->', jsonStart)
          const jsonStr = contentToProcess.substring(jsonStart, jsonEnd).trim()
          keywordsData = JSON.parse(jsonStr)
        } catch (e) {
          console.log('解析关键词数据出错:', e)
        }
      } else {
        // 如果没有FINAL_RESULT标记，尝试直接解析final_result或content为JSON
        if (typeof result === 'object' && result.final_result) {
          try {
            // 尝试直接解析final_result为JSON
            keywordsData = JSON.parse(result.final_result)
          } catch (e) {
            console.log('直接解析final_result失败:', e)
            // 如果直接解析失败，尝试从final_result中寻找JSON片段
            try {
              const jsonMatch = result.final_result.match(/\{[\s\S]*?\}/g)
              if (jsonMatch && jsonMatch.length > 0) {
                keywordsData = JSON.parse(jsonMatch[0])
              }
            } catch (e2) {
              console.log('从final_result寻找JSON片段也失败:', e2)
            }
          }
        }

        // 如果还没有解析到数据，尝试从完整的content中寻找JSON
        if (!keywordsData && contentToProcess) {
          try {
            const jsonMatch = contentToProcess.match(/\{[\s\S]*?"all_keywords"[\s\S]*?\}/g)
            if (jsonMatch && jsonMatch.length > 0) {
              keywordsData = JSON.parse(jsonMatch[0])
            }
          } catch (e) {
            console.log('从完整content寻找关键词JSON失败:', e)
          }
        }
      }

      console.log('解析的关键词数据:', keywordsData)

      if (keywordsData && keywordsData.all_keywords) {
        const allKeywords = keywordsData.all_keywords || []
        const keywordsText = allKeywords.join('\n')

        console.log('提取的所有关键词:', allKeywords)
        console.log('关键词文本:', keywordsText)

        // 弹出对话框显示结果并询问是否应用到当前分类
        this.$confirm(
          `AI成功提取了 ${allKeywords.length} 个关键词：\n\n${keywordsText.substring(0, 200)}${keywordsText.length > 200 ? '...' : ''}\n\n是否将这些关键词应用到当前分类的锚文本关键词字段中？`,
          'AI关键词提取完成',
          {
            confirmButtonText: '应用关键词',
            cancelButtonText: '仅查看',
            type: 'success',
            width: '600px'
          }
        ).then(() => {
          // 用户选择应用关键词，直接填充到锚文本关键词字段
          this.applyKeywordsToField(keywordsText, keywordsData)
        }).catch(() => {
          // 用户选择仅查看，显示成功消息
          this.$message.success('AI关键词提取完成！您可以手动复制使用这些关键词。')
        })
      } else {
        // 如果没有解析到关键词数据，显示原始结果和调试信息
        console.log('未能解析到关键词数据')
        console.log('处理的内容:', contentToProcess)
        this.$message.warning('AI关键词提取完成，但未能解析到关键词数据。请查看控制台日志进行调试。')
      }
    },
    applyKeywordsToField(keywordsText, keywordsData) {
      // 直接应用关键词到当前编辑的分类字段
      if (this.temp.anchor_text_keywords) {
        // 如果已有关键词，询问是否替换还是追加
        this.$confirm(
          '当前已有锚文本关键词，是否要替换为AI提取的关键词？',
          '关键词应用方式',
          {
            confirmButtonText: '替换',
            cancelButtonText: '追加',
            type: 'info',
            distinguishCancelAndClose: true
          }
        ).then(() => {
          // 用户选择替换
          this.temp.anchor_text_keywords = keywordsText
          this.$message.success('AI关键词已替换到锚文本关键词字段！')
        }).catch((action) => {
          if (action === 'cancel') {
            // 用户选择追加
            this.temp.anchor_text_keywords = this.temp.anchor_text_keywords + '\n' + keywordsText
            this.$message.success('AI关键词已追加到锚文本关键词字段！')
          }
        })
      } else {
        // 如果没有关键词，直接填入
        this.temp.anchor_text_keywords = keywordsText
        this.$message.success('AI关键词已填入锚文本关键词字段！')
      }
    },
    // 预览相关方法
    handlePreview(row) {
      this.previewCategory = row
      this.generatePreviewHtml(row)
      this.previewVisible = true
    },

    // 跳转到预览修改页面
    handlePreviewEdit(row) {
      this.$router.push({
        path: '/static-site/category-preview-editor/',
        query: {
          category_id: row.id,
          category_name: row.name,
          site_id: this.siteId,
          site_name: this.siteName,
          html_content: row.html_content || ''
        }
      })
    },
    generatePreviewHtml(category) {
      const html = category.html_content || this.getDefaultContent(category)

      // 简单的HTML预览
      let previewContent = html

      // 如果有模板，可以在这里处理模板结合
      if (category.template && category.template.html_content) {
        // 这里可以添加模板和分类内容的结合逻辑
        previewContent = category.template.html_content.replace('{{content}}', html)
      }

      // 如果HTML内容不是完整的HTML文档，包装一下
      if (previewContent && !previewContent.includes('<html>') && !previewContent.includes('<!DOCTYPE')) {
        previewContent = `
          <!DOCTYPE html>
          <html>
          <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>${category.name || '分类预览'}</title>
            <style>
              body { font-family: Arial, sans-serif; margin: 20px; line-height: 1.6; }
              h1, h2, h3 { color: #333; }
              .category-info { background: #f5f7fa; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
            </style>
          </head>
          <body>
            <div class="category-info">
              <h2>分类信息</h2>
              <p><strong>分类名称:</strong> ${category.name || '未知分类'}</p>
              <p><strong>别名:</strong> ${category.slug || '未设置'}</p>
              <p><strong>描述:</strong> ${category.description || '暂无描述'}</p>
            </div>
            <div class="category-content">
              ${previewContent}
            </div>
          </body>
          </html>
        `
      }

      this.previewHtml = previewContent
    },
    getDefaultContent(category) {
      return `
        <div style="padding: 40px; text-align: center; color: #666; font-family: Arial, sans-serif;">
          <h2 style="color: #409EFF; margin-bottom: 20px;">分类预览</h2>
          <div style="background: #f5f7fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
            <h3 style="margin-top: 0; color: #303133;">分类名称：${category.name}</h3>
            <p style="color: #606266; margin: 10px 0;">别名：${category.slug}</p>
            <p style="color: #606266; margin: 10px 0;">描述：${category.description || '暂无描述'}</p>
          </div>
          <div style="background: #fff3cd; padding: 15px; border-radius: 4px; border: 1px solid #ffeaa7;">
            <p style="margin: 0; color: #856404;">该分类暂无HTML内容，请编辑分类添加HTML内容后再进行预览。</p>
          </div>
        </div>
      `
    },
    openFullPreview() {
      this.previewVisible = false
      this.fullPreviewVisible = true
    },
    handleQuickPreview() {
      // 使用当前编辑的分类数据进行预览
      this.previewCategory = this.temp
      this.generatePreviewHtml(this.temp)
      this.previewVisible = true
    },
    // AI生成分类页面HTML内容
    async handleAIGenerateCategory() {
      // 检查是否为编辑模式且有分类ID
      if (this.action !== 'edit' || !this.temp.id) {
        this.$message.warning('请先保存分类后再使用AI生成功能')
        return
      }

      // 确认对话框
      const confirmResult = await this.$confirm(
        '使用AI生成分类页面HTML内容会替换当前的HTML内容，是否继续？',
        'AI生成分类页面',
        {
          confirmButtonText: '继续生成',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => false)

      if (!confirmResult) {
        return
      }

      // 首先保存当前的分类设置（包括max_link_products等）
      try {
        await this.saveCategory()
      } catch (error) {
        this.$message.error('保存分类设置失败，无法继续AI生成')
        return
      }

      // 设置AI任务参数
      this.aiTaskParams = {
        task_name: 'ai_generate_category_page',
        category_id: this.temp.id
      }

      // 显示AITask组件并触发开始分析
      this.$nextTick(() => {
        if (this.$refs.aiGenerateCategoryTask) {
          this.$refs.aiGenerateCategoryTask.handleShowDialog()
        }
      })
    },
    // 保存分类（内部方法）
    async saveCategory() {
      const _data = this.temp

      return new Promise((resolve, reject) => {
        updateStaticSiteCategory(_data.id, _data).then(response => {
          if (response.success) {
            resolve(response)
          } else {
            reject(new Error(response.msg))
          }
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 处理AI任务结果（分类页面生成完成）
    handleAICategoryResult(result) {
      console.log('AI分类页面生成结果:', result)

      // 解析结果数据
      let resultData = null
      try {
        // 检查result的类型和结构
        if (typeof result === 'string') {
          // 如果result是字符串，可能是JSON字符串
          resultData = JSON.parse(result)
        } else if (typeof result === 'object' && result !== null) {
          // 如果result是对象，可能已经是解析后的数据
          resultData = result
        }

        console.log('解析后的结果数据:', resultData)
      } catch (e) {
        console.error('解析AI任务结果失败:', e)
        console.error('原始结果:', result)
        this.$message.error('AI任务结果解析失败')
        return
      }

      if (resultData && resultData.success) {
        // 构建成功消息
        const messageLines = [
          `AI分类页面生成成功！`,
          `分类名称: ${resultData.category_name}`,
          `内容长度: ${resultData.content_length} 字符`,
          `产品链接: ${resultData.related_products_count} 个`
        ]

        if (resultData.template_used) {
          messageLines.push(`使用模板: ${resultData.template_used}`)
        }

        if (resultData.scene_images && resultData.scene_images.length > 0) {
          messageLines.push(`场景图片: ${resultData.scene_images.length} 张`)
        }

        if (resultData.html_validation && resultData.html_validation.message) {
          messageLines.push(`HTML验证: ${resultData.html_validation.message}`)
        }

        const message = messageLines.join('\n')

        this.$notify({
          title: '分类页面生成成功',
          message: message,
          type: 'success',
          duration: 8000
        })

        // 重新获取分类信息以更新HTML内容到编辑框
        this.refreshCategoryData()

        // 在控制台输出详细信息
        console.log('生成的HTML内容长度:', resultData.content_length)

        if (resultData.scene_images && resultData.scene_images.length > 0) {
          console.log('生成的场景图片URLs:', resultData.scene_images)
        }

        if (resultData.menu_data) {
          console.log('集成的菜单数据:', resultData.menu_data)
        }

        if (resultData.html_validation) {
          console.log('HTML验证结果:', resultData.html_validation)
        }
      } else {
        // 处理失败情况
        let errorMsg = '未知错误'

        if (resultData && resultData.msg) {
          errorMsg = resultData.msg
        } else if (resultData && resultData.error) {
          errorMsg = resultData.error
        } else if (!resultData) {
          errorMsg = '未能获取到结果数据'
        }

        this.$message.error(`AI分类页面生成失败: ${errorMsg}`)
        console.error('AI分类页面生成失败:', resultData)
      }
    },
    // 刷新分类数据
    async refreshCategoryData() {
      if (!this.temp.id) {
        console.log('没有分类ID，无法刷新数据')
        return
      }

      try {
        // AI生成完成后，列表数据是旧的，需要重新获取最新数据
        console.log('AI生成完成，重新获取列表数据以获取最新的HTML内容')
        await this.getListAndUpdateTemp()
      } catch (error) {
        console.error('刷新分类数据失败:', error)
        this.$message.error('刷新分类数据失败，请手动刷新页面')
      }
    },
    // 获取列表数据并更新当前编辑的分类
    async getListAndUpdateTemp() {
      try {
        // 先尝试获取包含当前编辑分类的完整数据
        const fullParams = {
          page: 1,
          pageSize: 1000, // 使用较大的pageSize确保包含所有数据
          site_id: this.siteId
          // 临时不使用搜索条件，确保能找到当前编辑的分类
        }

        const fullResponse = await getStaticSiteCategoryList(new URLSearchParams(fullParams).toString())

        if (fullResponse.success) {
          const fullData = fullResponse.data.data || []

          // 更新当前编辑的分类数据
          if (this.temp.id) {
            const updatedCategory = fullData.find(item => item.id === this.temp.id)
            if (updatedCategory) {
              this.temp = Object.assign({}, updatedCategory)
              this.temp.site = this.siteId
              // 修复字段映射：后端返回template_id，前端使用template
              this.temp.template = this.temp.template_id || null

              console.log('分类数据已从完整列表更新:', this.temp)
              this.$message.success('HTML内容已刷新到编辑框')
            } else {
              console.log('在完整列表中未找到当前编辑的分类')
              this.$message.warning('未找到当前编辑的分类，请重新打开编辑')
            }
          }

          // 然后重新获取当前页面的显示数据
          const displayParams = {
            page: this.listQuery.page,
            pageSize: this.listQuery.pageSize,
            site_id: this.siteId
          }
          if (this.kwInput) {
            displayParams.search = this.kwInput
          }

          const displayResponse = await getStaticSiteCategoryList(new URLSearchParams(displayParams).toString())

          if (displayResponse.success) {
            this.data = displayResponse.data.data
            this.total = displayResponse.data.total
            this.parentCategories = displayResponse.data.data.filter(item => !item.parent)
          }
        } else {
          this.$message.error('获取数据失败：' + fullResponse.msg)
        }
      } catch (error) {
        console.error('获取列表数据失败:', error)
        this.$message.error('获取数据失败：' + (error.response && error.response.data && error.response.data.msg ? error.response.data.msg : error.message))
      }
    },
    // AI根据模板生成HTML内容
    async handleAIGenerateWithTemplate() {
      // 验证必需的条件
      if (!this.temp.template) {
        this.$message.error('请先选择一个模板')
        return
      }

      if (!this.temp.name || !this.temp.name.trim()) {
        this.$message.error('请先输入分类名称')
        return
      }

      // 检查是否为编辑模式
      if (this.action !== 'edit' || !this.temp.id) {
        this.$message.warning('请先保存分类后再使用AI生成功能')
        return
      }

      // 确认对话框
      const confirmResult = await this.$confirm(
        '使用AI生成分类页面HTML内容会替换当前的HTML内容，是否继续？',
        'AI生成分类页面',
        {
          confirmButtonText: '继续生成',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => false)

      if (!confirmResult) {
        return
      }

      // 首先保存当前的分类设置（包括模板选择等）
      try {
        await this.saveCategory()
      } catch (error) {
        this.$message.error('保存分类设置失败，无法继续AI生成')
        return
      }

      // 设置AI任务参数 - 改为使用ai_generate_category_page
      this.aiTaskParams = {
        task_name: 'ai_generate_category_page',
        category_id: this.temp.id
      }

      // 显示AITask组件并触发开始分析
      this.$nextTick(() => {
        if (this.$refs.aiGenerateCategoryTask) {
          this.$refs.aiGenerateCategoryTask.handleShowDialog()
        }
      })
    },
    // 处理AI模板生成结果 - 现在统一使用ai_generate_category_page
    handleAITemplateResult(result) {
      // 重用handleAICategoryResult方法处理结果
      this.handleAICategoryResult(result)
    },

    // 快速导航替换（仅替换导航部分）
    handleFastNavigationReplace(category) {
      this.currentNavigationCategory = category
      this.selectedMenuId = null
      this.getMenuList()
      this.menuSelectDialogVisible = true
    },

    // 获取菜单列表
    getMenuList() {
      const params = {
        site_id: this.siteId,
        page: 1,
        pageSize: 100
      }

      getStaticSiteMenuList(new URLSearchParams(params).toString())
        .then(response => {
          if (response.success) {
            this.menuList = response.data.data || []
          } else {
            this.$message.error('获取菜单列表失败：' + response.msg)
          }
        }).catch(err => {
          console.log(err)
          this.$message.error('获取菜单列表失败：' + (err.response && err.response.data && err.response.data.msg ? err.response.data.msg : err.message))
        })
    },

    // 获取菜单类型标签
    getMenuTypeLabel(type) {
      const menuTypeOptions = [
        { value: 'main', label: '主导航' },
        { value: 'footer', label: '页脚导航' },
        { value: 'sidebar', label: '侧边导航' },
        { value: 'breadcrumb', label: '面包屑导航' }
      ]
      const option = menuTypeOptions.find(item => item.value === type)
      return option ? option.label : type
    },

    // 确认导航替换
    confirmNavigationReplace() {
      if (!this.selectedMenuId) {
        this.$message.error('请选择要替换的菜单')
        return
      }

      const selectedMenu = this.menuList.find(menu => menu.id === this.selectedMenuId)
      if (!selectedMenu) {
        this.$message.error('选择的菜单不存在')
        return
      }

      this.menuSelectDialogVisible = false

      this.$confirm(
        '确定要进行AI智能导航替换吗？\n\n此操作将使用AI智能分析分类 "' + this.currentNavigationCategory.name + '" 的完整HTML结构，并将菜单 "' + selectedMenu.name + '" 的内容智能集成到现有导航中。\n\n✨ AI处理特点：\n• 自动保留原有logo和关键链接\n• 智能集成新菜单项\n• 保持原有样式和响应式设计\n• 优化用户体验',
        '确认AI智能导航替换',
        {
          confirmButtonText: '开始AI处理',
          cancelButtonText: '取消',
          type: 'info'
        }
      ).then(() => {
        this.fastNavigationReplace(this.currentNavigationCategory, this.selectedMenuId)
      }).catch(() => {
        // 用户取消
      })
    },

    async fastNavigationReplace(category, menuId) {
      // 显示加载提示
      const loading = this.$loading({
        lock: true,
        text: '🤖 AI正在智能分析HTML结构并集成导航菜单...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      try {
        const requestData = {
          category_id: category.id,
          menu_id: menuId,
          api_key: this.$store.getters.ai_task_api_key || 'test_key_for_development',
          engine: 'default'
        }

        const response = await aiRebuildCategoryNavigationOnly(requestData)

        loading.close()

        if (response.success) {
          const result = response.data || {}
          const debugInfo = result.debug_info || {}

          // 根据HTML是否更新显示不同的消息
          if (result.html_updated) {
            this.$message({
              type: 'success',
              message: 'AI智能导航替换完成，HTML内容已更新',
              duration: 3000
            })
          } else {
            this.$message({
              type: 'warning',
              message: 'AI导航替换完成，但HTML内容可能未发生变化',
              duration: 5000
            })
          }

          // 显示详细结果
          let resultMessage = 'AI智能导航替换结果：\n\n'
          resultMessage += `分类名称: ${result.category_name || category.name}\n`
          resultMessage += `处理状态: ${result.success ? '成功' : '失败'}\n`
          resultMessage += `HTML更新状态: ${result.html_updated ? '已更新' : '未更新'}\n`
          resultMessage += `导航项总数: ${result.navigation_items || 0}\n`
          resultMessage += `原有菜单项保留: ${result.functional_items_preserved || 0}\n`
          resultMessage += `新增菜单项: ${result.category_items_added || 0}\n`
          resultMessage += `处理方式: ${result.replacement_method || 'AI智能集成'}\n`

          if (result.ai_processed) {
            resultMessage += `\nAI处理特点:\n`
            resultMessage += `• 智能保留原有logo和关键链接\n`
            resultMessage += `• 自动集成新菜单项\n`
            resultMessage += `• 保持原有样式和结构\n`
          }

          if (debugInfo.html_content_changed !== undefined) {
            resultMessage += `\n调试信息:\n`
            resultMessage += `原始HTML长度: ${debugInfo.original_html_length || 0}\n`
            resultMessage += `更新HTML长度: ${debugInfo.updated_html_length || 0}\n`
            resultMessage += `HTML内容变化: ${debugInfo.html_content_changed ? '是' : '否'}\n`
          }

          this.$alert(resultMessage, '替换完成', {
            confirmButtonText: '确定',
            type: result.html_updated ? 'success' : 'warning'
          })

          // 刷新列表
          this.getList()
        } else {
          this.$message.error('快速导航替换失败：' + (response.msg || '未知错误'))
        }
      } catch (error) {
        loading.close()
        console.error('快速导航替换失败:', error)
        this.$message.error('快速导航替换失败：' + (error.response && error.response.data && error.response.data.msg ? error.response.data.msg : error.message))
      }
    },

    // AI分类菜单重构相关方法
    handleRebuildCategoryMenu(category) {
      this.$confirm('确定要重构此分类的菜单吗？此操作将用数据库中的菜单配置替换分类中的菜单部分，内容部分保持不变。', '确认重构', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.rebuildCategoryMenu(category)
      }).catch(() => {
        // 用户取消
      })
    },

    async rebuildCategoryMenu(category) {
      this.menuRebuildLoading = true
      this.currentRebuildCategory = category
      this.menuRebuildLog = ''
      this.menuRebuildLogVisible = true

      try {
        const apiKey = this.$store.getters.ai_task_api_key || 'test_key_for_development'
        if (!apiKey) {
          this.$message.error('请先在系统设置中配置AI API密钥')
          this.menuRebuildLoading = false
          return
        }

        const requestData = {
          category_id: category.id,
          api_key: apiKey,
          engine: 'default'
        }

        await aiRebuildCategoryMenuStream(
          requestData,
          (message) => {
            // 进度更新
            this.menuRebuildLog += message
            this.$nextTick(() => {
              // 滚动到底部
              const logElement = document.querySelector('.menu-rebuild-log')
              if (logElement) {
                logElement.scrollTop = logElement.scrollHeight
              }
            })
          },
          (result) => {
            // 完成
            this.menuRebuildLoading = false
            this.menuRebuildLog += '\n\n=== 重构完成 ===\n'
            this.menuRebuildLog += `分类ID: ${result.category_id}\n`
            this.menuRebuildLog += `分类名称: ${result.category_name}\n`
            this.menuRebuildLog += `重构状态: ${result.success ? '成功' : '失败'}\n`
            this.menuRebuildLog += `集成的菜单类型: ${result.menu_types_integrated ? result.menu_types_integrated.join(', ') : '无'}\n`
            this.menuRebuildLog += `菜单项总数: ${result.total_menu_items || 0}\n`

            if (result.success) {
              this.$message.success('分类菜单重构完成')
              this.getList() // 刷新列表
            } else {
              this.$message.error('分类菜单重构失败')
            }
          },
          (error) => {
            // 错误
            this.menuRebuildLoading = false
            this.menuRebuildLog += '\n\n❌ 重构失败: ' + error + '\n'
            this.$message.error('分类菜单重构失败: ' + error)
          }
        )
      } catch (error) {
        this.menuRebuildLoading = false
        this.menuRebuildLog += '\n\n❌ 重构失败: ' + error.message + '\n'
        this.$message.error('分类菜单重构失败: ' + error.message)
      }
    }
  }
}
</script>

<style scoped>
.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-dialog {
  margin: 88px auto !important;
}

.preview-container {
  height: 100%;
}

.preview-header {
  padding: 10px 0;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 15px;
}

.preview-iframe-container {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.full-preview-dialog >>> .el-dialog__body {
  padding: 10px 20px;
}

.full-preview-container {
  width: 100%;
  height: 100%;
}
</style>
